package com.zrrd.gmall.order.controller;

import com.zrrd.gmall.cart.feign.CartFeignClient;
import com.zrrd.gmall.common.result.Result;
import com.zrrd.gmall.common.util.AuthContextHolder;
import com.zrrd.gmall.model.cart.CartInfo;
import com.zrrd.gmall.model.order.OrderDetail;
import com.zrrd.gmall.model.order.OrderInfo;
import com.zrrd.gmall.model.user.UserAddress;
import com.zrrd.gmall.order.service.OrderService;
import com.zrrd.gmall.product.fegin.ProductFeignClient;
import com.zrrd.gmall.user.feign.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/order")
public class OrderApiController {
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductFeignClient productFeignClient;
    //确认订单
    @GetMapping("/auth/trade")
    public Result<Map<String,Object>> trade(HttpServletRequest request){
        //获取id
        String userId = AuthContextHolder.getUserId(request);
        //地址
        List<UserAddress> userAddressList = userFeignClient.findUserAddressByUserId(userId);
        //商品
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);
        //创建一个结果
        List<OrderDetail> detailList = new ArrayList<>();
        for (CartInfo cartInfo : cartCheckedList) {
            //创建一个对象接受
            OrderDetail detail = new OrderDetail();
            detail.setSkuId(cartInfo.getSkuId());
            detail.setSkuName(cartInfo.getSkuName());
            detail.setSkuNum(cartInfo.getSkuNum());
            detail.setImgUrl(cartInfo.getImgUrl());
            detail.setOrderPrice(cartInfo.getSkuPrice());
            //添加进集合
            detailList.add(detail);
        }

        //计算总金额
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(detailList);
        orderInfo.sumTotalAmount();

        Map<String,Object> map =new HashMap<>();
        map.put("userAddressList",userAddressList);
        map.put("detailArrayList",detailList);
        map.put("totalNum",detailList.size());
        map.put("totalAmount",orderInfo.getTotalAmount());
        //存入流水号
        String tradeNo = orderService.getTradeNo(userId);
        map.put("tradeNo",tradeNo);
        //返回结果
        return Result.ok(map);
    }
    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request){

        //设置用户Id
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        //存订单号
        String tradeNo = request.getParameter("tradeNo");
        if (!orderService.checkTradeNo(userId,tradeNo)){
            return Result.fail().message("不能重复提交订单!");
        }
        //删除流水号
        orderService.deleteTradeNo(userId);
        /*获得订单明细集合*/
        List<OrderDetail> orderDetailList =orderInfo.getOrderDetailList();
        for (OrderDetail detail : orderDetailList) {
            //验证库存
            boolean b = orderService.checkStock(detail.getSkuId(), detail.getSkuNum());
            if (!b){
                return Result.fail().message(detail.getSkuName()+"库存不足！");
            }
            //验证价格
            BigDecimal skuPrice =productFeignClient.getSkuPrice(detail.getSkuId());
            System.out.println("detail.getPrice==========>"+detail.getOrderPrice());
            System.out.println("skuPrice============>"+skuPrice);
            if (detail.getOrderPrice().compareTo(skuPrice)!=0){
                //更新钱

                cartFeignClient.loadCartCache(userId);
                return Result.fail().message(detail.getSkuName()+"价格有变动！");
            }
        }
        //执行保存订单
        Long orderId = orderService.saveOrderInfo(orderInfo);
        //返回订单id
        return Result.ok(orderId);
    }
    @GetMapping("/inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable("orderId")Long orderId){
        return orderService.getOrderInfo(orderId);
    }
}
